package so.ifl.commons.tools.pinter.impl;

import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;

import so.ifl.commons.tools.DateUtil;
import so.ifl.commons.tools.StringHelper;
import so.ifl.commons.tools.pinter.Iprinter;
import so.ifl.servcie.StudentService;
import so.ifl.vo.StudentVo;

/**
 *create by aaron.lu
 *create at 2012-2-22 下午10:52:49
 *<mailto: atyuan.lu@gmail.com>
 **/
public class BodyCheckPrinter implements Iprinter {
	
	Logger logger_ = LoggerFactory.getLogger(this.getClass());
	
	
	private String lineSeparator = (String) java.security.AccessController.doPrivileged(new sun.security.action.GetPropertyAction("line.separator"));//换行符
	private String LIST_ = "list";

	@Override
	public void print(Map<String, Object> data, HttpServletResponse response, HttpServletRequest request) throws Exception {
		logger_.debug("param:" + data);
		List<StudentVo> list = (List<StudentVo>)data.get(LIST_);
		
		if (null != list && list.size() > 0) {
			StudentVo studentVo = list.get(0);
			
			ByteArrayOutputStream baos = new ByteArrayOutputStream();// 用于存储每页生成PDF流
			String servletPath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() +request.getContextPath();
			String model_path = servletPath + "/templates/body_check.pdf";
			PdfReader reader = new PdfReader(model_path);
			BaseFont baseFontChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
			
			PdfStamper pdfStamper = new PdfStamper(reader, baos);			
			AcroFields form = pdfStamper.getAcroFields(); 
			form.addSubstitutionFont(baseFontChinese);
			
			form.setField("have", "√");
			form.setField("studentName", studentVo.getStudentName());
			form.setField("officeName", studentVo.getOfficeName());
			String studentSex = null != studentVo.getStudentSex() && studentVo.getStudentSex().intValue() == 1 ? "男":"女";
			form.setField("studentSex", studentSex);
			form.setField("studentBirthday", null == studentVo.getStudentBirthday()? "":DateUtil.YMD_SDF_POINT.format(studentVo.getStudentBirthday()));
			if (studentVo.getStudentCertificateType().equals("sl")) {
				form.setField("studentCertificateType", "居民身份证");
			}else if(studentVo.getStudentCertificateType().equals("sj")){
				form.setField("studentCertificateType", "居民身份证");
			}else{
				form.setField("studentCertificateType", studentVo.getStudentCertificateType());
			}
			String studentCertificateNumber = studentVo.getStudentCertificateNumber();
			for (int i = 0; i < studentCertificateNumber.length(); i++) {
				if (i < 18) {
					form.setField("n" + i, studentCertificateNumber.substring(i, i + 1));
				}
			}
			
			form.setField("studentApplyDriveType", studentVo.getStudentApplyDriveType());
			String studentContactAddress = studentVo.getStudentContactAddress();
			if (null != studentContactAddress && studentContactAddress.length() > 15) {
				form.setField("studentContactAddress1", studentContactAddress.substring(0, 15));
				form.setField("studentContactAddress2", studentContactAddress.substring(15, studentContactAddress.length()));
			}else{
				form.setField("studentContactAddress3", studentContactAddress);
			}
//			String result = studentContactAddress.substring(0, 17) + lineSeparator + studentContactAddress.substring(17, studentContactAddress.length());
//			logger_.debug(result);
		
			form.setField("studentDriveNowNumber", studentVo.getStudentDriveNowNumber());
			form.setField("studentNationality", studentVo.getStudentNationality());
			form.setField("studentPhone", studentVo.getStudentPhone());
			
			pdfStamper.setFormFlattening(true); // 千万不漏了这句啊, */
			pdfStamper.close();
			
			ServletOutputStream out = response.getOutputStream();			
			response.setContentType("application/pdf");
			
			baos.writeTo(out);
			out.flush();						
			
			baos.close();
			
		}
	}

	@Override
	public Map<String, Object> getData(HttpServletRequest request)throws Exception {
		String studentId = request.getParameter("studentId");
		Map<String, Object> result = new HashMap<String, Object>();
		
		if (StringHelper.isNotEmpty(studentId)) {
		
			
			ServletContext servletContext = request.getSession().getServletContext();		
			ApplicationContext appctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
			
			StudentService studentService = (StudentService)appctx.getBean("studentService");
			
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("student_id_", studentId);
 			
			List<StudentVo> list = studentService.queryStudentWithParamAndPagination(params, 0, 1);
			
			result.put(LIST_, list);
		}		

		return result;
	}

}
